1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
/*!
Identity types
*/
use super::*;

/// The reflexivity axiom: asserts that the left hand side and right hand side are judgementally equal, and therefore propositionally equal
#[derive(Debug, Clone)]
pub struct Refl {
    /// The left hand side of the equality
    left: TermId,
    /// The right hand side of the equality
    right: TermId,
    /// The type of this proof
    annot: Option<Annotation>,
    /// This proof's code
    code: Code,
    /// This proof's filter
    filter: VarFilter,
    /// This proof's flags
    flags: AtomicTyckFlags,
}

impl Refl {
    /// Create a new, unchecked instance of the reflexivity axiom with a given annotation
    #[inline]
    pub fn new_unchecked_with(left: TermId, right: TermId, annot: Option<Annotation>) -> Refl {
        let code = Self::compute_code(&left, &right, annot.as_ref());
        let filter = Self::compute_filter(&left, &right, annot.as_ref());
        let flags = Self::compute_flags(&left, &right, annot.as_ref()).into();
        Refl {
            left,
            right,
            annot,
            code,
            filter,
            flags,
        }
    }

    /// Compute the most basic identity type for a given instance of the reflexivity axiom
    #[inline]
    pub fn compute_ty(
        left: &TermId,
        right: &TermId,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Option<Id> {
        if let Some(universe) = Id::compute_ty(left, right) {
            Some(Id::new_unchecked_with(
                left.clone_into_id_with(ctx),
                right.clone_into_id_with(ctx),
                Annotation::from_ty(universe.into_id_with(ctx)).ok(),
            ))
        } else {
            None
        }
    }

    /// Create a new, unchecked instance of the reflexivity axiom, inferring the most basic possible annotation
    #[inline]
    pub fn new_unchecked(left: TermId, right: TermId, ctx: &mut (impl ConsCtx + ?Sized)) -> Refl {
        let annot = if let Some(ty) = Self::compute_ty(&left, &right, ctx) {
            Annotation::from_ty(ty.into_id_with(ctx)).ok()
        } else {
            None
        };
        Self::new_unchecked_with(left, right, annot)
    }

    /// Compute the code of a reflexivity instance with a given type annotation
    #[inline]
    pub fn compute_code(left: &TermId, right: &TermId, annot: Option<&Annotation>) -> Code {
        let mut hasher = AHasher::new_with_keys(0x362, 0x6423);
        let left = left.code();
        let right = right.code();
        left.pure().hash(&mut hasher);
        right.pure().hash(&mut hasher);
        let pre = hasher.finish();
        annot.hash(&mut hasher);
        let post = hasher.finish();
        Code::new(pre, post)
    }

    /// Compute the filter of a reflexivity instance with a given type annotation
    #[inline]
    pub fn compute_filter(left: &TermId, right: &TermId, annot: Option<&Annotation>) -> VarFilter {
        left.get_filter()
            .union(right.get_filter())
            .union(annot.get_filter())
    }

    /// Compute the flags of a reflexivity instance with a given type annotation
    #[inline]
    pub fn compute_flags(left: &TermId, right: &TermId, annot: Option<&Annotation>) -> TyckFlags {
        TyckFlags::default().with_flag(
            TyckFlag::GlobalTyck,
            L4::with_false(!annot.maybe_tyck())
                & L4::from(left.maybe_tyck())
                & L4::from(right.maybe_tyck()),
        )
    }

    /// Compute whether a dependent function type locally type-checks given an annotation
    pub fn compute_local_tyck(left: &TermId, right: &TermId, annot: AnnotationRef) -> bool {
        if let Term::Id(id) = &*annot.base() {
            Self::compute_local_tyck_id(left, right, id)
        } else {
            false
        }
    }

    /// Compute whether a dependent function type locally type-checks given an identity type
    pub fn compute_local_tyck_id(left: &TermId, right: &TermId, id: &Id) -> bool {
        left.eq_in(id.left(), &mut Untyped).unwrap_or(false)
            && right.eq_in(id.right(), &mut Untyped).unwrap_or(false)
    }

    /// Get the left-hand-side, i.e. source, of this path
    pub fn left(&self) -> &TermId {
        &self.left
    }

    /// Get the right hand side, i.e. target, of this path
    pub fn right(&self) -> &TermId {
        &self.right
    }

    /// Get the left and right hand side of this path if *equivalent*
    pub fn as_equal(&self) -> Option<&TermId> {
        //TODO: looser definition of equivalence?
        if self.left == self.right {
            Some(&self.left)
        } else {
            None
        }
    }

    /// Get the left and side of this path if different from the right hand side
    pub fn diff_right(&self) -> Option<&TermId> {
        if self.left != self.right {
            Some(&self.right)
        } else {
            None
        }
    }

    /// If both sides of this equality are universes, return one.
    /// Return `None` if neither side is a universe, or if both sides are different universes (implying this instance is invalid!)
    pub fn as_universe(&self) -> Option<Universe> {
        match (&*self.left, &*self.right) {
            (Term::Universe(left), Term::Universe(right)) => {
                let left = left.as_universe();
                let right = right.as_universe();
                if left == right {
                    Some(left.clone())
                } else {
                    None
                }
            }
            (Term::Universe(u), _) | (_, Term::Universe(u)) => Some(u.as_universe().clone()),
            _ => None,
        }
    }

    /// If the right side of this equality is a pi type, return it.
    pub fn as_pi(&self) -> Option<&Pi> {
        if let Term::Pi(pi) = &*self.right {
            Some(pi)
        } else {
            None
        }
    }

    /// Attempt to transport the right side of this path in a given typing context.
    pub fn transport_right(
        &self,
        target: &TermId,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<Refl>, Error> {
        if *target == self.right {
            return Ok(None);
        }
        self.transported_right(target, ctx).map(Some)
    }

    /// Get this path transported right in a given typing context
    pub fn transported_right(
        &self,
        target: &TermId,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Refl, Error> {
        let right_eq = self.right.eq_in(target, ctx.eq_ctx());
        match right_eq {
            Some(true) | None => Ok(Refl::new_unchecked(
                self.left.clone(),
                target.clone(),
                ctx.cons_ctx(),
            )),
            Some(false) => Err(Error::TermMismatch),
        }
    }

    /// Get this instance of reflexivity as a coerced annotation
    pub fn coerce_right(
        &self,
        target: &TermId,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<Annotation>, Error> {
        if *target == self.right {
            return Ok(None);
        }
        let result = if let Some(true) = self.left.is_subtype(target) {
            Annotation::from_ty(target.clone())?
        } else {
            Annotation::from_path(
                self.transported_right(target, ctx)?
                    .into_id_with(ctx.cons_ctx()),
            )?
        };
        Ok(Some(result))
    }

    /// Convert this annotation into it's equal sides, or error if unequal
    pub fn into_equal(self) -> Result<TermId, Refl> {
        if self.left == self.right {
            Ok(self.left)
        } else {
            Err(self)
        }
    }
}

/// The identity type, representing proofs that two terms are equal
#[derive(Debug, Clone)]
pub struct Id {
    /// The left hand side of the (potential) equality
    left: TermId,
    /// The right hand side of the (potential) equality
    right: TermId,
    /// The type of this type
    annot: Option<Annotation>,
    /// This type's code
    code: Code,
    /// This type's filter
    filter: VarFilter,
    /// This type's flags
    flags: AtomicTyckFlags,
}

impl Id {
    /// Create a new, unchecked instance of an identity type with a given annotation
    #[inline]
    pub fn new_unchecked_with(left: TermId, right: TermId, annot: Option<Annotation>) -> Id {
        let code = Self::compute_code(&left, &right, annot.as_ref());
        let filter = Self::compute_filter(&left, &right, annot.as_ref());
        let flags = Self::compute_flags(&left, &right, annot.as_ref()).into();
        Id {
            left,
            right,
            annot,
            code,
            filter,
            flags,
        }
    }

    /// Compute the most basic universe for an identity type
    #[inline]
    pub fn compute_ty(left: &TermId, right: &TermId) -> Option<Universe> {
        if let (Some(left), Some(right)) = (left.annot(), right.annot()) {
            if let (Some(left), Some(right)) = (left.as_universe(), right.as_universe()) {
                return Some(left.join(&right));
            }
        }
        None
    }

    /// Create a new, unchecked instance of the reflexivity axiom, inferring the most basic possible annotation
    #[inline]
    pub fn new_unchecked(left: TermId, right: TermId, ctx: &mut (impl ConsCtx + ?Sized)) -> Id {
        let annot = if let Some(ty) = Self::compute_ty(&left, &right) {
            Annotation::from_ty(ty.into_id_with(ctx)).ok()
        } else {
            None
        };
        Self::new_unchecked_with(left, right, annot)
    }

    /// Compute the code of an identity type with a given type annotation
    #[inline]
    pub fn compute_code(left: &TermId, right: &TermId, annot: Option<&Annotation>) -> Code {
        let mut hasher = AHasher::new_with_keys(0x5322, 0x7532);
        let left = left.code();
        let right = right.code();
        left.pure().hash(&mut hasher);
        right.pure().hash(&mut hasher);
        let pre = hasher.finish();
        left.hash(&mut hasher);
        right.hash(&mut hasher);
        annot.hash(&mut hasher);
        let post = hasher.finish();
        Code::new(pre, post)
    }

    /// Compute the filter of a reflexivity instance with a given type annotation
    #[inline]
    pub fn compute_filter(left: &TermId, right: &TermId, annot: Option<&Annotation>) -> VarFilter {
        left.get_filter()
            .union(right.get_filter())
            .union(annot.get_filter())
    }

    /// Compute the flags of a reflexivity instance with a given type annotation
    #[inline]
    pub fn compute_flags(left: &TermId, right: &TermId, annot: Option<&Annotation>) -> TyckFlags {
        TyckFlags::default().with_flag(
            TyckFlag::GlobalTyck,
            L4::with_false(!annot.maybe_tyck())
                & L4::from(left.maybe_tyck())
                & L4::from(right.maybe_tyck()),
        )
    }

    /// Compute whether a dependent function type locally type-checks given an annotation
    pub fn compute_local_tyck(left: &TermId, right: &TermId, annot: AnnotationRef) -> bool {
        if let Term::Universe(base) = &*annot.base() {
            Self::compute_local_tyck_universe(left, right, base.as_universe())
        } else {
            false
        }
    }

    /// Compute whether a dependent function type locally type-checks given a universe
    pub fn compute_local_tyck_universe(left: &TermId, right: &TermId, base: &Universe) -> bool {
        if let (Some(left), Some(right)) = (left.annot(), right.annot()) {
            if let (Some(left), Some(right)) = (left.as_universe(), right.as_universe()) {
                return left <= *base && right <= *base;
            }
        }
        false
    }

    /// Get the left-hand-side, i.e. source, of this path
    pub fn left(&self) -> &TermId {
        &self.left
    }

    /// Get the right hand side, i.e. target, of this path
    pub fn right(&self) -> &TermId {
        &self.right
    }

    /// If both sides of this equality are types, get them as a universe.
    /// Return `None` if neither side is a universe, or if both sides are different universes (implying this instance is invalid!)
    pub fn as_universe(&self) -> Option<Universe> {
        match (&*self.left, &*self.right) {
            (Term::Universe(left), Term::Universe(right)) => {
                let left = left.as_universe();
                let right = right.as_universe();
                if left == right {
                    Some(left.clone())
                } else {
                    None
                }
            }
            (Term::Universe(u), _) | (_, Term::Universe(u)) => Some(u.as_universe().clone()),
            _ => None,
        }
    }
}

impl Cons for Refl {
    type Consed = Refl;

    fn cons(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Self::Consed> {
        let left = self.left.cons(ctx);
        let right = self.right.cons(ctx);
        let annot = self.annot.cons(ctx);
        if left.is_none() && right.is_none() && annot.is_none() {
            None
        } else {
            let left = left.unwrap_or_else(|| self.left.clone());
            let right = right.unwrap_or_else(|| self.right.clone());
            let annot = annot.unwrap_or_else(|| self.annot.clone());
            Some(Refl {
                left,
                right,
                annot,
                code: self.code,
                filter: self.filter,
                flags: self.flags.clone(),
            })
        }
    }

    #[inline]
    fn to_consed_ty(&self) -> Self::Consed {
        self.clone()
    }
}

impl Substitute for Refl {
    type Substituted = Refl;

    fn subst_rec(&self, ctx: &mut (impl SubstCtx + ?Sized)) -> Result<Option<Refl>, Error> {
        let left = self.left.subst_rec(ctx)?;
        let right = self.right.subst_rec(ctx)?;
        let annot = self.annot.cons(ctx.cons_ctx());
        if left.is_none() && right.is_none() && annot.is_none() {
            Ok(None)
        } else {
            let left = left.unwrap_or_else(|| self.left.clone());
            let right = right.unwrap_or_else(|| self.right.clone());
            let annot = annot.unwrap_or_else(|| self.annot.clone());
            let code = Self::compute_code(&left, &right, annot.as_ref());
            let filter = Self::compute_filter(&left, &right, annot.as_ref());
            let flags = Self::compute_flags(&left, &right, annot.as_ref()).into();
            Ok(Some(Refl {
                left,
                right,
                annot,
                code,
                filter,
                flags,
            }))
        }
    }

    #[inline]
    fn from_consed(this: Self::Consed, _ctx: &mut (impl ConsCtx + ?Sized)) -> Self::Substituted {
        this
    }
}

impl HasDependencies for Refl {
    fn has_var_dep(&self, ix: u32, equiv: bool) -> bool {
        self.filter.contains(ix)
            && (self.filter.exact()
                || self.left.has_var_dep(ix, equiv)
                || self.right.has_var_dep(ix, equiv)
                || self.annot.has_var_dep(ix, equiv))
    }

    fn has_dep_below(&self, ix: u32, base: u32) -> bool {
        if let Some(contains) = self.filter.contains_below(ix, base) {
            contains
        } else {
            self.left.has_dep_below(ix, base)
                || self.right.has_dep_below(ix + 1, base + 1)
                || self.annot.has_dep_below(ix, base)
        }
    }

    #[inline]
    fn get_filter(&self) -> VarFilter {
        self.filter
    }
}

impl TermEq for Refl {
    fn eq_in(&self, other: &Self, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        if let Some(result) =
            ctx.approx_term_eq_code((self.code, Form::BetaEta), (other.code, Form::BetaEta))
        {
            return result;
        }
        let annot = if ctx.cmp_annot() {
            self.annot.eq_in(&other.annot, ctx)
        } else if ctx.cmp_var() {
            Some(self.annot.is_some() == other.annot.is_some())
        } else {
            Some(true)
        };
        if let Some(false) = annot {
            return Some(false);
        }
        let left = self.left.eq_in(&other.left, ctx);
        if let Some(false) = left {
            return Some(false);
        }
        let right = self.right.eq_in(&other.right, ctx);
        if let Some(false) = right {
            return Some(false);
        }
        Some(annot? && left? && right?)
    }
}

impl Typecheck for Refl {
    fn do_local_tyck(&self, _ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        if let Some(annot) = &self.annot {
            Self::compute_local_tyck(&self.left, &self.right, annot.borrow_annot())
        } else {
            false
        }
    }

    fn do_global_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        Some(
            self.left.tyck(ctx)?
                && self.right.tyck(ctx)?
                && self.left.eq_in(&self.right, ctx.eq_ctx())?,
        )
    }

    fn do_annot_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        self.annot.tyck(ctx)
    }

    fn load_flags(&self) -> TyckFlags {
        self.flags.load_flags()
    }

    fn set_flags(&self, flags: TyckFlags) {
        self.flags.set_flags(flags);
    }
}

impl Value for Refl {
    type ValueConsed = Refl;
    type ValueSubstituted = Refl;

    #[inline]
    fn into_term_direct(self) -> Term {
        Term::Refl(self)
    }

    #[inline]
    fn annot(&self) -> Option<AnnotationRef> {
        self.annot.as_ref().map(Annotation::borrow_annot)
    }

    #[inline]
    fn is_local_ty(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_universe(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_function(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_pi(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_root(&self) -> bool {
        true
    }

    #[inline]
    fn coerce(
        &self,
        _ty: Option<TermId>,
        _ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<Refl>, Error> {
        //TODO: this
        Err(Error::NotImplemented)
    }

    fn annotate_unchecked(
        &self,
        _annot: Annotation,
        _ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<Refl>, Error> {
        //TODO: this
        Err(Error::NotImplemented)
    }

    #[inline]
    fn is_subtype_in(
        &self,
        _other: &Term,
        _ctx: &mut (impl TermEqCtxMut + ?Sized),
    ) -> Option<bool> {
        // refl instances are never types!
        Some(false)
    }

    #[inline]
    fn universe(&self) -> Option<Universe> {
        None
    }

    #[inline]
    fn code(&self) -> Code {
        self.code
    }

    #[inline]
    fn untyped_code(&self) -> Code {
        Self::compute_code(&self.left, &self.right, None)
    }

    #[inline]
    fn eq_term_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        match other {
            Term::Refl(other) => self.eq_in(other, ctx),
            _ => Some(false),
        }
    }

    #[inline]
    fn form(&self) -> Form {
        //TODO: lhs normalization?
        Form::BetaEta
    }
}

impl Eq for Refl {}

impl PartialEq for Refl {
    fn eq(&self, other: &Self) -> bool {
        self.eq_in(other, &mut Structural).unwrap_or(false)
    }
}

impl Cons for Id {
    type Consed = Id;

    fn cons(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Self::Consed> {
        let left = self.left.cons(ctx);
        let right = self.right.cons(ctx);
        let annot = self.annot.cons(ctx);
        if left.is_none() && right.is_none() && annot.is_none() {
            None
        } else {
            let left = left.unwrap_or_else(|| self.left.clone());
            let right = right.unwrap_or_else(|| self.right.clone());
            let annot = annot.unwrap_or_else(|| self.annot.clone());
            Some(Id {
                left,
                right,
                annot,
                code: self.code,
                filter: self.filter,
                flags: self.flags.clone(),
            })
        }
    }

    #[inline]
    fn to_consed_ty(&self) -> Self::Consed {
        self.clone()
    }
}

impl Substitute for Id {
    type Substituted = Id;

    fn subst_rec(&self, ctx: &mut (impl SubstCtx + ?Sized)) -> Result<Option<Id>, Error> {
        let left = self.left.subst_rec(ctx)?;
        let right = self.right.subst_rec(ctx)?;
        let annot = self.annot.cons(ctx.cons_ctx());
        if left.is_none() && right.is_none() && annot.is_none() {
            Ok(None)
        } else {
            let left = left.unwrap_or_else(|| self.left.clone());
            let right = right.unwrap_or_else(|| self.right.clone());
            let annot = annot.unwrap_or_else(|| self.annot.clone());
            let code = Self::compute_code(&left, &right, annot.as_ref());
            let filter = Self::compute_filter(&left, &right, annot.as_ref());
            let flags = Self::compute_flags(&left, &right, annot.as_ref()).into();
            Ok(Some(Id {
                left,
                right,
                annot,
                code,
                filter,
                flags,
            }))
        }
    }

    #[inline]
    fn from_consed(this: Self::Consed, _ctx: &mut (impl ConsCtx + ?Sized)) -> Self::Substituted {
        this
    }
}

impl HasDependencies for Id {
    fn has_var_dep(&self, ix: u32, equiv: bool) -> bool {
        self.filter.contains(ix)
            && (self.filter.exact()
                || self.left.has_var_dep(ix, equiv)
                || self.right.has_var_dep(ix, equiv)
                || self.annot.has_var_dep(ix, equiv))
    }

    fn has_dep_below(&self, ix: u32, base: u32) -> bool {
        if let Some(contains) = self.filter.contains_below(ix, base) {
            contains
        } else {
            self.left.has_dep_below(ix, base)
                || self.right.has_dep_below(ix, base)
                || self.annot.has_dep_below(ix, base)
        }
    }

    #[inline]
    fn get_filter(&self) -> VarFilter {
        self.filter
    }
}

impl TermEq for Id {
    fn eq_in(&self, other: &Self, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        if let Some(result) =
            ctx.approx_term_eq_code((self.code, Form::BetaEta), (other.code, Form::BetaEta))
        {
            return result;
        }
        let annot = if ctx.cmp_annot() {
            self.annot.eq_in(&other.annot, ctx)
        } else if ctx.cmp_var() {
            Some(self.annot.is_some() == other.annot.is_some())
        } else {
            Some(true)
        };
        if let Some(false) = annot {
            return Some(false);
        }
        let left = self.left.eq_in(&other.left, ctx);
        if let Some(false) = left {
            return Some(false);
        }
        let right = self.right.eq_in(&other.right, ctx);
        if let Some(false) = right {
            return Some(false);
        }
        Some(annot? && left? && right?)
    }
}

impl Typecheck for Id {
    fn do_local_tyck(&self, _ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        if let Some(annot) = &self.annot {
            Self::compute_local_tyck(&self.left, &self.right, annot.borrow_annot())
        } else {
            false
        }
    }

    fn do_global_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        Some(self.left.tyck(ctx)? && self.right.tyck(ctx)?)
    }

    fn do_annot_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        self.annot.tyck(ctx)
    }

    fn load_flags(&self) -> TyckFlags {
        self.flags.load_flags()
    }

    fn set_flags(&self, flags: TyckFlags) {
        self.flags.set_flags(flags);
    }
}

impl Value for Id {
    type ValueConsed = Id;
    type ValueSubstituted = Id;

    #[inline]
    fn into_term_direct(self) -> Term {
        Term::Id(self)
    }

    #[inline]
    fn annot(&self) -> Option<AnnotationRef> {
        self.annot.as_ref().map(Annotation::borrow_annot)
    }

    #[inline]
    fn is_local_ty(&self) -> Option<bool> {
        Some(true)
    }

    #[inline]
    fn is_local_universe(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_function(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_pi(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_root(&self) -> bool {
        true
    }

    #[inline]
    fn coerce(
        &self,
        _ty: Option<TermId>,
        _ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<Id>, Error> {
        //TODO: this
        Err(Error::NotImplemented)
    }

    fn annotate_unchecked(
        &self,
        _annot: Annotation,
        _ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<Id>, Error> {
        //TODO: this
        Err(Error::NotImplemented)
    }

    #[inline]
    fn is_subtype_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        if let Term::Id(other) = other {
            Some(self.left.eq_in(&other.left, ctx)? && self.right.eq_in(&other.right, ctx)?)
        } else {
            Some(false)
        }
    }

    #[inline]
    fn code(&self) -> Code {
        self.code
    }

    #[inline]
    fn untyped_code(&self) -> Code {
        Self::compute_code(&self.left, &self.right, None)
    }

    #[inline]
    fn eq_term_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        match other {
            Term::Id(other) => self.eq_in(other, ctx),
            _ => Some(false),
        }
    }

    #[inline]
    fn form(&self) -> Form {
        //TODO: lhs normalization?
        Form::BetaEta
    }
}

impl Eq for Id {}

impl PartialEq for Id {
    fn eq(&self, other: &Self) -> bool {
        self.eq_in(other, &mut Structural).unwrap_or(false)
    }
}